import 'dart:io';

import 'package:aliyun_vod_upload/aliyun_vod_upload.dart';
import 'package:aliyun_vod_upload/model/UploadFileInfoModel.dart';
import 'package:aliyun_vod_upload/model/authInitModel.dart';
import 'package:aliyun_vod_upload/model/stsInitModel.dart';
import 'package:aliyun_vod_upload/model/vodInfoModel.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:aliyun_vod_upload/model/vodUploadResultModel.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:aliyun_vod_upload/aliyun_vod_upload.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: const Home(),
      ),
    );
  }
}


class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();

  addListener() async {
    AliyunVodUpload.addListener(
      onUploadStartedListener: (UploadFileInfoModel fileInfoModel) {
        print('开始上传监听: ${fileInfoModel.toJson()}');
      },
      onUploadProgressListener: (UploadFileInfoModel fileInfoModel, uploadedSize, totalSize) {
        print('上传进度监听: ${uploadedSize / totalSize}');
      },
      onUploadFinishedListener: (UploadFileInfoModel fileInfoModel, VodUploadResultModel resultMode) {
        print('上传完成监听: ${resultMode.toJson()}');
      },
      onUploadTokenExpiredListener: () {
        print('token失效');
      }
    );
  }

  _fileAdd(BuildContext context) async{
    final List<AssetEntity>? assets = await AssetPicker.pickAssets(context, pickerConfig: const AssetPickerConfig(maxAssets: 1, requestType: RequestType.video));
    if(assets?.isNotEmpty ?? false) {
      final file = await assets![0].file;
      bool result = await AliyunVodUpload.addFile(file?.path ?? '', VodInfoModel(
          title: '未知标题',
          desc: "测试描述",
          cateId: 0,
          tags: ["1"],
          coverUrl: ""
      ));
      print('返回状态码：$result');
    }
  }
  _fileDel() async{

  }
  _fileCancel() async{

  }
  _fileRepty() async{

  }

  _getList() async{

  }
  _clearList() async{

  }

  _uploadStart() async{
    bool result = await AliyunVodUpload.startUpload();
  }
  _uploadStop() async{

  }
  _uploadCancel() async{

  }
  _uploadRepty() async{

  }

  @override
  void initState() {
    super.initState();
    initStsUpLoad();
  }

  initStsUpLoad() async{
    if(Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      var response = await Dio().get(
          'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=test&FileName=test.mp4&BusinessType=vodai&TerminalType=iphone&DeviceModel=${iosInfo.model}&UUID=${iosInfo.identifierForVendor}&AppVersion=1.0.0'
      );
      AliyunVodUpload.initAuthUpLoader(AuthInitModel(
          uploadAddress: response.data['UploadAddress'],
          uploadAuth: response.data['UploadAuth']
      ));
    } else {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      var response = await Dio().get(
          'http://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=xxx.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0'
      );
      AliyunVodUpload.initAuthUpLoader(AuthInitModel(
          uploadAddress: response.data['UploadAddress'],
          uploadAuth: response.data['UploadAuth']
      ));
    }
    addListener();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(38.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text('文件管理'),
              SizedBox(height: 10,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                      onTap: () {
                        _fileAdd(context);
                      },
                      child: const Text('添加', style: TextStyle(color: Colors.blue),)
                  ),
                  GestureDetector(
                      onTap: () {
                        _fileDel();
                      },
                      child: const Text('删除', style: TextStyle(color: Colors.blue),)
                  ),
                  GestureDetector(
                      onTap: () {
                        _fileCancel();
                      },
                      child: const Text('取消', style: TextStyle(color: Colors.blue),)
                  ),
                  GestureDetector(
                      onTap: () {
                        _fileRepty();
                      },
                      child: const Text('恢复', style: TextStyle(color: Colors.blue),)
                  ),
                ],
              )
            ],
          ),
          SizedBox(height: 10,),
          Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text('文件管理'),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  GestureDetector(
                      onTap: () {
                        _getList();
                      },
                      child: const Text('获取', style: TextStyle(color: Colors.blue),)
                  ),
                  GestureDetector(
                      onTap: () {
                        _clearList();
                      },
                      child: const Text('清除', style: TextStyle(color: Colors.blue),)
                  ),
                ],
              )
            ],
          ),
          SizedBox(height: 10,),
          Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text('上传管理'),
              SizedBox(height: 10,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                      onTap: () {
                        _uploadStart();
                      },
                      child: const Text('开始', style: TextStyle(color: Colors.blue),)
                  ),
                  GestureDetector(
                      onTap: () {
                        _uploadStop();
                      },
                      child: const Text('停止', style: TextStyle(color: Colors.blue),)
                  ),
                  GestureDetector(
                      onTap: () {
                        _uploadCancel();
                      },
                      child: const Text('暂停', style: TextStyle(color: Colors.blue),)
                  ),
                  GestureDetector(
                      onTap: () {
                        _uploadRepty();
                      },
                      child: const Text('恢复', style: TextStyle(color: Colors.blue),)
                  ),
                ],
              )
            ],
          )
        ],
      ),
    );
  }
}
